/*
 * Copyright (C) 2020 Agrui
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


#include "IpcSimClient.h"
#include "IpcClient.h"
#include "IpcClientLoader.h"
#include "IpcService.h"
#include "IpcApi.h"


IPC_API_RESULT_T ipcInit() {
    ipcChannelLoad();
    return IPC_API_RESULT_OK;
}

static void onChannelStateChanged(void* callbackData, int id, int state) {
    ipcStateChangedCallback cb = (ipcStateChangedCallback)callbackData;
    if (cb) {
        cb(id, state);
    }
}

void registerIpcStateChanged(int subId, int serviceId, ipcStateChangedCallback callback) {
    IpcChannelManager* manager = getDefaultIpcChannelManager();
    registerIpcChannelStateChanged(manager, subId, onChannelStateChanged, (void*)callback);
}

void registerServiceStateChanged(int subId, int serviceId, ipcServiceStateChangedCallback callback) {
    IpcChannelManager* manager = getDefaultIpcChannelManager();
    //registerIpcChannelStateChanged(manager, subId)
}


IPC_HANDLER ipcServiceInit(int subId, int serviceId) {
    IPC_HANDLER handler = INVALID_IPC_HANDLE;
    void* client = NULL;
    if (serviceId == IPC_SERVICE_SIM) {
        client = new IpcSimClient(subId);
    }
    handler = OBJECT_TO_IPC_HANDLER(client);
    return handler;
}

void ipcServiceDeinit(IPC_HANDLER handler) {
    IpcClient* client = IPC_CLIENT_FROM_IPC_HANDLER(handler);
    if (client != nullptr) {
        delete client;
    }
}


IPC_API_RESULT_T ipcBindClient(IPC_HANDLER handler) {
    IpcClient* client = IPC_CLIENT_FROM_IPC_HANDLER(handler);
    return client->bindSubscription();
}

void ipcDeinit() {
    ipcChannelUnload();
}


IPC_API_RESULT_T ipcGetSimState(IPC_HANDLER handler, void* userData, ipcServiceResultCallback callback) {
    IpcSimClient* client = IPC_SIM_CLIENT_FROM_HANDLER(handler);
    return client->getSimState(userData, callback);
    return IPC_API_RESULT_OK;
}

